import http from '@/api/http.js'
import store from '@/store/index.js'

const requestUserInfo = function(code, avatar, nickName, obj, url, authCode){
	let params = {
		method: 'api/v2/member_login/login_by_alipay',
		code,
		avatar,
		nickName,
		authCode
	}
	http(params).then(res => {
		if(res.status){
			uni.setStorageSync('nickname', nickName);
			uni.setStorageSync('headimg', avatar);
			uni.setStorageSync('access_token', res.data.zfb_data.access_token);
			uni.setStorageSync('refresh_token', res.data.zfb_data.refresh_token);
			uni.setStorageSync('alipay_user_id', res.data.zfb_data.alipay_user_id);
			uni.setStorageSync('openid', res.data.zfb_data.user_id);
			if(res.data.token){
				uni.hideLoading();
				store.commit('login', res.data.memberInfo);
				uni.setStorageSync('token', res.data.token);
				uni.setStorageSync('userInfo', res.data.memberInfo);
				obj.userInfo = {...res.data.memberInfo};
				obj.isLogin = obj.$store.state.hasLogin;
				console.log(url);
				if(url){
					uni.navigateTo({
						url: url
					})
				}
			}else{
				uni.hideLoading();
				uni.navigateTo({
					url: '/platforms/mp-alipay/login/phone'
				})
			}
		}
	})
};

export default function(obj, url){
	return new Promise((resolve, reject) => {
		//主动授权：auth_user，静默授权：auth_base。或者其它scope。如需同时获取用户多项授权，可在 scopes 中传入多个 scope 值。
		my.getAuthCode({
			scopes: ['auth_base'],
			success: (res) => {
				console.log(res.authCode,123);
				if(res.authCode){
					let authCode = res.authCode;
					my.getOpenUserInfo({
						fail: (res) => {
							reject(res);
						},
						success: (res) => {
							console.log(res);
							let info = JSON.parse(res.response).response // 以下方的报文格式解析两层 response
							if(info.msg == 'Success'){
								let code = info.code;
								let avatar = info.avatar;
								let nickName = info.nickName;
								// uni.showLoading({
								// 	title: '登录中...'
								// })
								console.log(code, avatar, nickName, obj, url, authCode);
								requestUserInfo(code, avatar, nickName, obj, url, authCode)
							}else{
								uni.showToast({
									title: info.subMsg,
									icon: 'none'
								})
							}
						},
					});
				}
			},
		});
	});
}